package za.co.chris.traintimes.database;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;

public class LineFinder {
	private final String LINE_PREFIX = "line_";
	private final Context context;

	public LineFinder(Context context) {
		this.context = context;
	}

	public List<String> makeLineCreateScripts() {
		String[] fileList;
		List<String> queryList = new ArrayList<String>();
		try {
			fileList = context.getAssets().list("lines");
			BufferedReader reader;
			StringBuilder builder = new StringBuilder();

			for (String fileName : fileList) {
				reader = new BufferedReader(new InputStreamReader(context.getAssets().open("lines/" + fileName)));
				String[] firstLineTokens = reader.readLine().split(",");
				reader.close();
				builder.append("CREATE TABLE ").append(fileName.substring(5, fileName.length() - 4)).append(" (_id integer primary key AUTOINCREMENT,");
				for (String column : firstLineTokens) {
					builder.append(column.replace(" ", "_")).append(" text,");
				}
				builder.setCharAt(builder.lastIndexOf(","), ' ');

				builder.append(");");
				queryList.add(builder.toString());
				builder.setLength(0);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return queryList;
	}

	public List<String> getTables() {
		String[] fileList = null;
		try {
			fileList = context.getAssets().list("lines");
		} catch (IOException e) {
		}
		List<String> tableNames = new ArrayList<String>();
		for (String tableName : fileList) {
			tableNames.add(tableName.substring(5, tableName.length() - 4));
		}
		return tableNames;
	}
}
